import enum_data.TypeDBRecord;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AuthForm extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JPasswordField psswdFld;
    private JComboBox cmbBx_Login;
    private int sizeWidth = 300;
    private int sizeHeight = 170;

    public AuthForm() {

        ResultSet userList;

        setSize(sizeWidth, sizeHeight);
        setResizable(false);
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        setTitle("Авторизация пользователя");

        //Размещаем окно по центру экрана
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int locationX = (screenSize.width - sizeWidth) / 2;
        int locationY = (screenSize.height - sizeHeight) / 2;
        setBounds(locationX, locationY, sizeWidth, sizeHeight);

        //region заполняем comboBox с логинами пользователей
        userList = TEDatabase.execQuery("SELECT login FROM tradexpert.user WHERE user.state = " + TypeDBRecord.RECORD_ENABLE);

        try {
            while (userList.next()) {
                String userListString = userList.getString(1);
                cmbBx_Login.addItem(userListString);
            }
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        cmbBx_Login.setSelectedIndex(-1);

        //endregion заполняем comboBox с логинами пользователей

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });
    }

    //проверяем логин и пароль
    private void onOK() {
        if (cmbBx_Login.getSelectedIndex() > -1) try {
            String login = cmbBx_Login.getSelectedItem().toString();

            Statement st = TEDatabase.connection.createStatement();
            ResultSet userList = st.executeQuery("SELECT password FROM tradexpert.user WHERE login = '" + login +"'");

            userList.next();
                if ((new StringBuilder().append(psswdFld.getPassword()).toString()).equals(userList.getString(1))){
                    Security.authorise = true;
                    dispose();
                }
                else {
                    Security.authorise = false;
                    cmbBx_Login.setSelectedIndex(-1);
                    psswdFld.setText("");
                    JOptionPane.showMessageDialog(null, "ОШИБКА АВТОРИЗАЦИИ!!!");
                }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void onCancel() {

        dispose();
    }
}
